<template>
  <el-dialog
    title="二维码"
    :visible.sync="dialogVisible"
    width="30%"
  >
    <div v-if="url" class="img-wrap">
      <img :src="url">
    </div>
    <p v-else>二维码缺失</p>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="url" type="success" @click="saveImg">保 存</el-button>
      <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mixImg } from 'mix-img'
import carBg from '@/assets/img/car_qrcode_bg.png'
import companyBg from '@/assets/img/company_qrcode_bg.png'
import { getCarQRCodeMix, getCompanyQRCodeMix , getCodeMix} from '@/tool/util'

export default {
  data () {
    return {
      dialogVisible: false,
      url: '',
      downloadName: ''
    }
  },
  methods: {
    async show (row, type) {
      if (!row.qrcode) {
        this.dialogVisible = true
        return
      }
      let mixConfig
      if (type === 'car') {
        this.downloadName = row.no
        mixConfig = getCarQRCodeMix(carBg, row.qrcode, row.no)
      } else {
        this.downloadName = row.name
        mixConfig = getCompanyQRCodeMix(companyBg, row.qrcode, row.name, row.address)
      }
      this.dialogVisible = true
      const res = await mixImg(mixConfig)
      this.url = res.data.base64
    },
    async showImg (row, type) {
      console.log(row)
      if (!row.healthPic && !row.travelPic) {
        this.dialogVisible = true
        return
      }
      let mixConfig

      if (type === 'xcm') {
        mixConfig = getCodeMix(row.travelPic)
      } else {
        mixConfig = getCodeMix(row.healthPic)
      }
      this.dialogVisible = true
      const res = await mixImg(mixConfig)
      this.url = res.data.base64
    },
    saveImg () {
      // 同源域名可以直接下载，非同源域名会在浏览器打开图片
      const a = document.createElement('a')
      a.download = this.downloadName || this.url
      a.target = '_blank'
      a.href = this.url
      document.body.appendChild(a)
      a.click();
      document.body.removeChild(a)
    }
  }
}
</script>

<style lang="scss" scoped>
.img-wrap {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;

  img {
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
